import { listIcons as listOssIcons, sign } from "./cos";

export const listBands = async () => {
  const res = await (await fetch("/api/bands")).json();
  if (res.code === 200) {
    return res.data;
  }
};

export const listIcons = async (bandName) => {
  const res = await (await fetch(`/api/icons?band=${bandName}`)).json();
  if (res.code === 200) {
    return res.data;
  }
};

export const svgoPipe = async (file) => {
  const reader = new FileReader();
  reader.readAsText(file);
  const svgText = await new Promise((resolve) => {
    reader.onload = function () {
      resolve(this.result);
    };
  });
  const res = await fetch("/api/svgPipe", {
    method: "POST",
    body: svgText,
  });
  const svgNext = await res.text();
  return svgNext;
};

export const generateBand = async (bandName) => {
  const icons = await listOssIcons(bandName);
  await fetch("/api/downloadBand", {
    method: "POST",
    body: JSON.stringify({
      bandName,
      icons: icons.map((icon) => ({
        name: `${icon.name}.svg`,
        url: sign(icon.url),
      })),
    }),
  });
  window.open(`/api/generateBand?band=${bandName}`);
};
